package com.csaba.connector.citi.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import com.csaba.connector.model.Account;
import com.csaba.connector.model.Amount;
import com.csaba.connector.model.HistoryItem;
import com.csaba.util.LoggerHelper;

public class AccountHistoryParser
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	public static String parseFileDownloadURL( final Reader reader ) throws IOException
	{
		return CitiParser.parseNextURL("ID", "F3", "action", reader);
	}

	private static HistoryItem parseHistoryItem( final String line, final Account account ) throws ParseException
	{
		final SimpleDateFormat dateFormat = CitiCodes.dateFormat.get();
		final DecimalFormat amountFormat = CitiCodes.amountFormat.get();
		
		final HistoryItem historyItem = new HistoryItem();
		
		final String[] items = line.split(CitiCodes.SEPARATOR_CVS);
		// valueDate
		final String valueDateString = items[0].replaceAll("\"", "");
		final Date valueDate = dateFormat.parse(valueDateString);
		historyItem.setDate(valueDate);
		// description
		final String description = items[1].replaceAll("\"", "");
		historyItem.setDescription(description.replaceAll("\\s+", "-"));
		// amount
		final String amountString = items[2].replaceAll("\"", "");
		final double amount = amountFormat.parse(amountString).doubleValue();
		historyItem.setAmount(new Amount(amount, account.getCurrency()));
		// owner
		final String accountNumber = items[4].replaceAll("\"", "");
		if ( account.getNumber().equals(accountNumber) )
			historyItem.setOwner(account);
		else
			logger.fine("account.getNumber and account number from CVS are not equal: " + account.getNumber() + " !="
					+ accountNumber);
		return historyItem;
	}

	public static HistoryItem[] parseAccountHistoryList( final Reader reader, final Account account )
			throws IOException, ParseException
	{
		BufferedReader in = null;

		final List<HistoryItem> historyItemList = new ArrayList<HistoryItem>();
		try
		{
			in = new BufferedReader(reader);
			String line;
			while ( ( line = in.readLine() ) != null )
			{
				historyItemList.add(parseHistoryItem(line, account));
			}
		}
		finally
		{
			in.close();
		}

		final HistoryItem[] result = new HistoryItem[historyItemList.size()];
		for ( int i = 0; i < historyItemList.size(); i++ )
		{
			result[i] = historyItemList.get(i);
		}

		return result;

	}

}
